<template>
  <el-upload
    class="avatar-uploader"
    :action="fileServerEndpoint"
    :show-file-list="false"
    name="image"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl.length" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { checkResult } from "@/utils/Rutil.js";
import { imageEndpoint } from "@/api/media/file/uploadFile";
// 定义上传文件路径绑定
const imageUrl = defineModel("imageUrl", {
  default: ref(""),
});
const fileServerEndpoint = imageEndpoint;
const handleAvatarSuccess = (response, uploadFile) => {
  console.log("response", response);
  console.log("uploadFile", uploadFile);
  // 如果请求成功
  if (checkResult(response)) {
    imageUrl.value = response.data;
  } else {
    ElMessage.error("上传失败");
  }
};

const beforeAvatarUpload = (rawFile) => {
  const uploadFileList = ["image/jpeg", "image/png"];
  // 检测上传
  let exists = uploadFileList.some((type) => type === rawFile.type);
  if (!exists) {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  console.log("允许上传");
  return true;
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>
